import os
from dotenv import load_dotenv, find_dotenv # 导入 find_dotenv 帮助定位
import openai
import httpx
from langchain_community.chat_models import ChatOpenAI

# 加载 .env 文件中的环境变量 (增强调试)
load_dotenv(dotenv_path=find_dotenv(usecwd=True), verbose=True, override=True)

# 从环境变量加载 API 密钥和基础 URL
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_BASE_URL")
model = os.getenv("DEFAULT_MODEL")
max_tokens = os.getenv("MAX_TOKENS_DEFAULT")

chat = ChatOpenAI(
    openai_api_base=base_url,
    request_timeout=httpx.Timeout(300.0, connect=60.0),
    max_retries=1,
    max_tokens=int(max_tokens),
    openai_api_key=os.environ["OPENAI_API_KEY"],
    model_name=model
)

from langchain.schema import (
    SystemMessage,
    HumanMessage,
    AIMessage
)

messages = [
    SystemMessage(content="You are a helpful assistant."),
    HumanMessage(content="Knock knock."),
    AIMessage(content="Who's there."),
    HumanMessage(content="Orange"),
]

res = chat(messages)
print("模型回复：", res.content)


# ... (后续的 OpenAI 客户端初始化、API 调用和错误处理代码保持不变) ...
# 配置 API 客户端
# client = OpenAI(
#     api_key=api_key,
#     base_url=base_url,
#     timeout=httpx.Timeout(300.0, connect=60.0),
#     max_retries=1,
# )
#
# # 准备 API 请求的消息体
# messages = [
#     {"role": "user", "content": "你好，你使用了什么模型？请用中文回答。"}
# ]
#
# # 发送请求并处理响应
# try:
#     print("正在尝试调用 OpenAI API...")
#     response = client.chat.completions.create(
#         model=model,
#         messages=messages,
#         max_tokens=int(max_tokens),
#         temperature=0.8,
#     )
#     if response.choices:
#         assistant_reply = response.choices[0].message.content
#         print("模型回复:", assistant_reply)
#     else:
#         print("未能从 API 获取有效回复。")
# except openai.AuthenticationError as e:
#     print(f"OpenAI API 认证失败: {e}")
#     print("这通常意味着 API 密钥无效或没有权限。请再次核对 .env 文件中的 OPENAI_API_KEY 是否为您从 uiuiAPI 获取的正确密钥。")
#     print(f"当前尝试使用的 API Key (来自 .env 或环境变量，部分显示): '{api_key[:5]}...{api_key[-4:]}'，Base URL 为: {base_url}")
# except openai.APIConnectionError as e:
#     print(f"无法连接到 OpenAI API: {e}")
# except openai.RateLimitError as e:
#     print(f"达到 OpenAI API速率限制: {e}")
# except openai.APIStatusError as e:
#     print(f"OpenAI API 返回了错误状态码: {e.status_code}")
#     print(f"响应详情: {e.response}")
# except Exception as e:
#     print(f"调用 API 时发生未知错误: {e}")
#     print(f"错误类型: {type(e).__name__}")